class Task < ActiveRecord::Base

  attr_protected []
  
  validates :name,
    :type_name,
    :initiator_id,
    :executor_id,
    :due_on,
    :status,
    :presence => true
  
  belongs_to :feed
  belongs_to :customer
  belongs_to :initiator,:class_name => 'User',:foreign_key => 'initiator_id'
  belongs_to :executor,:class_name => 'User',:foreign_key => 'executor_id'
  
  # 当前企业
  default_scope lambda {where(:enterprise_id => Enterprise.current_id ).order('created_at asc')}
  # 我的
  scope :mine, lambda { where(:executor_id => User.current)}
  scope :assigned, lambda {where('initiator_id = ? and executor_id != ? ',User.current_id, User.current_id)}
  
  # 逾期
  scope :overdue, lambda { where(' due_on < ?',Date.today)  }

  # 今天
  scope :today, lambda { where(' due_on = ?',Date.today)  }

  # 明天
  scope :tomorrow, lambda { where( :due_on => 1.days.from_now.to_date) }

  # 本周
  scope :this_week, lambda { where('due_on between ? and ? ', 2.days.from_now.at_beginning_of_day, Date.today.at_end_of_week)}

  # 下周
  scope :next_week, lambda { where('due_on between ? and ?', 1.weeks.from_now.at_beginning_of_week, 1.weeks.from_now.at_end_of_week)}

  # 本月
  scope :this_month, lambda { where('due_on between ? and ? ', 2.weeks.from_now.at_beginning_of_week, Date.today.at_end_of_month)}
  
  # 随后(下个月以后)
  scope :later, lambda { where('due_on >= ?  ', 1.month.from_now.at_beginning_of_month.to_date)}

  # 完成的
  scope :completed, lambda {where(:status => 'completed')}
  # 待完成
  scope :waiting, lambda {where(:status => 'waiting')}
      
  before_validation do |task|
    # task.order_item_id ||= feed.try(:order_item_id)
    task.executor_id ||= User.current.id
    task.initiator_id ||= User.current.id
#    task.enterprise_id ||= Enterprise.current_id
  end

  # 自己给自己的？
  def assigned_by_and_to_current_user?
    assigned_by_current_user? and assigned_to_current_user?
  end

  # 当前用户指派的
  def assigned_by_current_user?
    initiator_id == User.current_id
  end

  # 指派给当前用户？
  def assigned_to_current_user?
    executor_id == User.current_id
  end

  def allow_to_be_edited_or_destroyed?
    initiator_id == User.current_id
  end
  
  def completed!
    update_attributes! :status => 'completed'
  end
  
  def waiting!
    update_attributes! :status => 'waiting'
  end
  
  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end

  # only_myself , everyone
  def visible_scope
    ActiveSupport::StringInquirer.new(self[:visible_scope])
  end

end
